import { Popup, TreeList } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import * as ReactDOMClient from 'react-dom/client';
import { CpasIcon } from '~/public/cpas-ui';
import './index.less';

const AddColCompany = React.forwardRef((props: any, ref: any) => {
  const [visible, setVisible] = useState<boolean>(false);
  const [visibleTreeList, setVisibleTreelist] = useState<boolean>(false);
  const [NameList, setNameList] = useState<any>([]);
  const Company = useRef<any>([]);
  const DeleteCompany = useRef<any>();

  useEffect(() => {
    if (visibleTreeList) {
      // setTimeout(() => {
      //   Company.current?.instance?.addRow();
      // }, 100); // 延时一小段时间，确保渲染完毕
    }
  }, [visibleTreeList]);
  // 自定义方法
  useImperativeHandle(ref, () => ({
    showPupop: async (namelist: any[], addcol?: any) => {
      setVisible(true);
      DeleteCompany.current = [];
      if (namelist.length) {
        setVisibleTreelist(true);
        setNameList(namelist);
      }
    },
  }));

  const insertRow = (e: any) => {
    if (e.data.name?.length && e.data.name.trim() > '') {
      if (NameList.filter((a: any) => a.name === e.data.name).length) {
        notify(`${e.data.name} 公司名字重复`, 'error', 1000);
        // e.cancel = true;
      }
    } else {
      notify('公司名字不能为空', 'error', 1000);
      // e.cancel = true;
    }
  };
  const onClickOK = async () => {
    await Company.current.instance.saveEditData();
    const list = Company.current.instance?.getDataSource()._items;
    if (list.filter((a: any) => a.data.name.trim() === '').length) {
      console.log(Company.current.instance?.getDataSource()._items, 'err');
      // notify('无新增的公司', 'error', 2000;
      notify('公司名字不能为空', 'error', 1000);
      return;
    }
    if (new Set(list.map((a: any) => a.data.name.trim())).size !== list.length) {
      notify(`公司名字重复`, 'error', 1000);
      return;
    }
    props.addCompanyCol(Company.current.instance?.getDataSource()._items, DeleteCompany.current);
    setVisibleTreelist(false);
    setVisible(false);
  };
  const onCellClick = (e: any) => {
    debugger;
  };
  const onRowRemoved = ({ data }: any) => {
    console.log('li', data);
    DeleteCompany.current.push(data.name);
    if (NameList.length === 0) {
      setVisibleTreelist(false);
    }
  };
  const onCellClickAddCompany = () => {
    setVisibleTreelist(true);
    setTimeout(() => Company.current?.instance?.addRow(), 100);
  };
  const dataRowRender = (cellElement: any, a: any, b: any, c: any) => {
    return ReactDOMClient.createRoot(cellElement).render(
      <>
        <CpasIcon
          type="icon-delete"
          fontSize={16}
          onClick={() => {
            Company.current.instance?.deleteRow(a.rowIndex);
          }}
        />
      </>,
    );
  };
  const treelist = () => {
    return (
      <>
        <TreeList
          ref={Company}
          dataSource={NameList}
          // key={'id'}
          height={'auto'}
          className="treeCompany"
          visible={visibleTreeList}
          keyExpr={'id'}
          showBorders={false}
          showRowLines={false}
          showColumnLines={false}
          showColumnHeaders={false}
          onRowInserting={insertRow}
          onRowRemoved={onRowRemoved}
          onContentReady={(e) => {
            console.log('li', 'TreeList 渲染完成');
            // Company.current?.instance?.addRow();
          }}
          // onCellClick={onCellClick}
          noDataText=""
          // newRowPosition={'viewportBottom'}
          // dataRowRender={dataRowRender}
          editing={{
            mode: 'cell',
            startEditAction: 'click',
            // allowDeleting: true,
            allowAdding: false,
            useIcons: true,
            confirmDelete: true,
          }}
          columns={[
            {
              dataField: 'name',
              // cellTemplate:dataRowRender,
              // allowEditing:true
            },
            {
              caption: '',
              alignment: 'right',
              // visible={button}
              fixed: true,
              fixedPosition: 'right',
              width: '40',
              cellTemplate: dataRowRender,
            },
          ]}
        />
        {/* <Column type={'button'}>1</Column> */}

        <CpasIcon type="icon-add-circle" fontSize={16} onClick={onCellClickAddCompany} />
      </>
    );
  };
  return (
    <>
      {visible && (
        <Popup
          title="添加同行公司"
          width={400}
          height={500}
          position={'right bottom'}
          contentRender={treelist}
          visible={visible}
          toolbarItems={[
            {
              widget: 'dxButton',
              location: 'after',
              options: {
                text: '取消',
                onClick: () => {
                  setVisibleTreelist(false);
                  setNameList([]);
                  setVisible(false);
                },
              },
              toolbar: 'bottom',
            },
            {
              widget: 'dxButton',
              toolbar: 'bottom',
              location: 'after',
              options: {
                text: '确定',
                onClick: onClickOK,
                type: 'default',
              },
            },
          ]}
          onHiding={() => {
            setVisibleTreelist(false);
            setNameList([]);
            setVisible(false);
          }}
        />
      )}
    </>
  );
});

export default AddColCompany;
